package org.example.runningforum.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.Key;
import java.util.Date;
import java.util.Map;


@Slf4j
@Service
public class JwtUtils {
    private static final long  EXPIRATION_TIME  = 60*60*1000;

    //key
    private static final String strKey = "PznodpqiVQ1qDR6OxU4ppSPQ9njepqDw0eaWD+/z5DxCD7dNWDb559KG9bKWvgvX";
    private static final Key key = Keys.hmacShaKeyFor(strKey.getBytes());


    /*
    * 生成token
    * */
    public static String genToken(Map<String,Object> claims){

        String token = Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRATION_TIME))
                .signWith(key)
                .compact();
        return token;
    }


    /*
    * 验证token
    * */
    public static Claims parseToken(String token){
        //参数校验
        if(!StringUtils.hasLength(token)){
            return null;
        }
        //开始校验
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try{
            claims = build.parseClaimsJws(token).getBody();
        } catch (Exception e) {
            log.error("验证失败，e:",e);
        }
        return claims;
    }

    /*
    * 获取Token中的ID
    * */

    public static Integer getUserInfoID(String token){
        Claims claims = parseToken(token);
        if(claims!=null){
            Integer id = (Integer) claims.get("id");
            return id;
        }else {
            return null;
        }
    }
}
